from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponseNotFound, HttpResponseForbidden
from django.shortcuts import render
from django.views import View
from xiaoyu_mall.apps.users.models import *

from .constants import PER_PRODUCTS_LIMIT as per_goods_num
from xiaoyu_mall.apps.contents.utils import get_categories
from xiaoyu_mall.apps.orders.models import TbOrderGoods
from .utils import get_breadcrumb


class ListView(View):
    """商品列表页"""
    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        # 校验参数category_id
        try:
            # 根据商品类别id获取该类的所有商品
            category = TbGoodsCategory.objects.get(id=category_id)
        except TbGoodsCategory.DoesNotExist:
            return HttpResponseNotFound('"参数category_id不存在"')
            # 商品排序
        # 接收sort参数，如果没有传递这个参数，那么使用默认的排序方式
        sort = request.GET.get('sort', 'default')
        # 默认排序 按价格排序 按人气排序
        if sort == 'price':
            sort_field = 'price'
        elif sort == 'hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = 'create_time'
        # 获取商品列表
        skus = category.tbsku_set.filter(is_launched=True).order_by(sort_field)
        # 分页功能
        # 创建分页器
        paginator = Paginator(skus, per_goods_num)  # 对skus进行分页，每页显示5条数据
        # 获取用户当前要看的那一页数据
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            return HttpResponseForbidden('Empty Page')
        # 获取总的页码数，前端分页插件中需要使用
        total_page = paginator.num_pages
        # 查询商品分类
        categories = get_categories()
        # 查询面包屑导航：一级 ==>二级==>一级
        breadcrumb = get_breadcrumb(category)

        # 获取每件商品的评价数量
        sku_li = []  # 保存当前页所有的sku_id
        skus = TbSku.objects.filter(category_id=category_id, is_launched=True)
        for sku in skus:
            sku_li.append(sku.id)
        # 获取每个sku-id的评论数量
        product_review_num = []
        for sid in sku_li:
            order_goods_list = TbOrderGoods.objects.filter(sku_id=sid, is_commented=True)
            # 保存每件商品的评价内容
            product_review_content = []
            for order_goods in order_goods_list:
                product_review_content.append(order_goods.comment)
            product_review_num.append(len(product_review_content))
        # 获取每页各个商品的评价数量,并保存到列表中
        per_review_num = [product_review_num[i:i + per_goods_num] for i in
                          range(0, len(product_review_num), per_goods_num)]
        # 获取当前访问各个商品的数量
        cur_per_review_num = per_review_num[page_skus.number - 1]
        # 将每个商品数量赋值给每个商品sku对象
        # 通过zip函数将sku对象和评价数量进行组合，格式为：[(sku对象,商品评价数量)]
        for sku in list(zip(page_skus, cur_per_review_num)):
            # 动态添加商品评价数量review_num属性
            sku[0].review_num = sku[1]

        context = {
            'category_id': category_id,
            'sort': sort,
            'page_skus': page_skus,
            'page_num': page_num,
            'total_page': total_page,
            'categories': categories,
            'breadcrumb': breadcrumb,
        }

        return render(request, 'list.html', context)